/**
 * 
 */
package com.hm.common.utils;

import java.util.HashMap;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * @author hwg
 *
 * 2020年12月28日
 */
public class JSONUtils {

	public static ObjectMapper mapper = new ObjectMapper();

	static {
		// 转换为格式化的json
		mapper.enable(SerializationFeature.INDENT_OUTPUT);
		// 如果json中有新增的字段并且是实体类类中不存在的，不报错
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}

	public static String toJson(Object value) throws JsonProcessingException {
		return mapper.writeValueAsString(value);
	}

	public static <T> T toObj(String json, Class<T> clazz) throws JsonProcessingException {
		return mapper.readValue(json, clazz);
	}
	
	public static void main(String[] args) throws JsonProcessingException {
		String json = toJson(new HashMap<String, Object>(){
			{
				put("uId", "00001");
				put("uName", "hwg");
			}
		});
		System.out.println(json);
		HashMap<String, Object> map = toObj(json, HashMap.class);
		System.out.println(map);
	}
}
